<div class="task-management">
<el-card class="box-card">
  <template #header>
    <div class="card-header">
      <h3>Task Management</h3>
      <div class="actions">
        <el-input
            v-model="searchQuery"
            placeholder="Search Tasks"
            prefix-icon="el-icon-search"
            clearable
            class="search-input"
            @input="handleSearch"
        />
        <el-button type="primary" @click="openCreateTaskDialog">
          <el-icon><CirclePlus /></el-icon>Create Task
        </el-button>
      </div>
    </div>
  </template>

  <el-tabs v-model="activeTab" class="task-tabs" @tab-click="handleTabClick">
    <el-tab-pane label="All Tasks" name="all"></el-tab-pane>
    <el-tab-pane label="Pending Review" name="review">
      <template #label>
        <span>Pending Review</span>
        <el-badge v-if="tasksPendingReviewCount > 0" :value="tasksPendingReviewCount" class="ml-1" />
      </template>
    </el-tab-pane>
    <el-tab-pane label="In Progress" name="in_progress"></el-tab-pane>
    <el-tab-pane label="Completed" name="completed"></el-tab-pane>
  </el-tabs>

  <el-table
      :data="filteredTasks"
      border
      style="width: 100%"
      v-loading="loading"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="id" label="ID" width="70" />
    <el-table-column prop="title" label="Title" min-width="200" />
    <el-table-column prop="status" label="Status" width="120">
      <template #default="scope">
        <el-tag :type="getStatusType(scope.row.status)">
          {{ scope.row.status }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="assigneeName" label="Assigned To" width="120">
      <template #default="scope">
        <span v-if="scope.row.assigneeName">{{ scope.row.assigneeName }}</span>
        <el-tag v-else type="info" size="small">Unassigned</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="completed" label="Progress" width="120">
      <template #default="scope">
        <el-progress 
            :percentage="calculateTaskProgress(scope.row)" 
            :status="scope.row.status === 'Completed' ? 'success' : ''"
        />
      </template>
    </el-table-column>
    <el-table-column prop="priority" label="Priority" width="100">
      <template #default="scope">
        <el-tag :type="getPriorityType(scope.row.priority)">
          {{ scope.row.priority || 'Medium' }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="startTime" label="Start Time" width="160" />
    <el-table-column prop="endTime" label="End Time" width="160" />
    <el-table-column label="Actions" width="180" fixed="right">
      <template #default="scope">
        <el-button type="primary" size="small" @click="viewTaskDetails(scope.row)">
          <el-icon><View /></el-icon>Details
        </el-button>
        <el-button type="success" size="small" @click="openAssignDialog(scope.row)" :disabled="!!scope.row.assigneeId">
          <el-icon><CirclePlus /></el-icon>Assign
        </el-button>
        <el-button type="warning" size="small" @click="editTask(scope.row)">
          <el-icon><Edit /></el-icon>Edit
        </el-button>
        <el-popconfirm
            title="Are you sure to delete this task?"
            @confirm="deleteTaskItem(scope.row.id)"
        >
          <template #reference>
            <el-button type="danger" size="small">
              <el-icon><Delete /></el-icon>Delete
            </el-button>
          </template>
        </el-popconfirm>
        <el-button type="success" size="small" @click="viewTaskSubmissions(scope.row)">
          <el-icon><Document /></el-icon>Files
        </el-button>
      </template>
    </el-table-column>
  </el-table>

  <div class="pagination-container">
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalTasks"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </div>
</el-card>

<!-- Task Details Dialog -->
<el-dialog
    v-model="detailsDialogVisible"
    title="Task Details"
    width="60%"
    destroy-on-close
>
  <el-descriptions
      v-if="currentTask"
      :column="2"
      border
  >
    <el-descriptions-item label="Task Title">{{ currentTask.title }}</el-descriptions-item>
    <el-descriptions-item label="Task Status">
      <el-tag :type="getStatusType(currentTask.status)">
        {{ currentTask.status }}
      </el-tag>
    </el-descriptions-item>
    <el-descriptions-item label="Assigned Student">
      <span v-if="currentTask.assigneeName">{{ currentTask.assigneeName }}</span>
      <el-tag v-else type="info">Unassigned</el-tag>
    </el-descriptions-item>
    <el-descriptions-item label="Priority">
      <el-tag :type="getPriorityType(currentTask.priority)">
        {{ currentTask.priority || 'Medium' }}
      </el-tag>
    </el-descriptions-item>
    <el-descriptions-item label="Start Time">{{ currentTask.startTime || 'Not Set' }}</el-descriptions-item>
    <el-descriptions-item label="End Time">{{ currentTask.endTime || 'Not Set' }}</el-descriptions-item>
    <el-descriptions-item label="Create Time">{{ currentTask.createTime }}</el-descriptions-item>
    <el-descriptions-item label="Update Time">{{ currentTask.updateTime }}</el-descriptions-item>
    <el-descriptions-item label="Task Description" :span="2">
      <div class="task-description">{{ currentTask.description || 'No description' }}</div>
    </el-descriptions-item>
  </el-descriptions>

  <!-- Task Evaluation Section -->
  <div v-if="currentTask && (currentTask.submissionCount > 0)" class="task-evaluation-section">
    <div class="section-header">
      <h3>Task Evaluation</h3>
    </div>
    <div v-loading="evaluationLoading">
      <el-form v-if="!currentEvaluation" :model="evaluationForm" label-width="80px">
        <el-form-item label="Score">
          <el-rate
              v-model="evaluationForm.score"
              :max="5"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              :texts="['1 point', '2 points', '3 points', '4 points', '5 points']"
              show-text
          />
        </el-form-item>
        <el-form-item label="Comment">
          <el-input
              v-model="evaluationForm.comment"
              type="textarea"
              :rows="3"
              placeholder="Enter comments on student completion"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEvaluation">Submit Evaluation</el-button>
        </el-form-item>
      </el-form>

      <el-descriptions v-else border :column="1" class="evaluation-details">
        <el-descriptions-item label="Score">
          <el-rate
              v-model="currentEvaluation.score"
              disabled
              :max="5"
              :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
          />
          {{ currentEvaluation.score }} points
        </el-descriptions-item>
        <el-descriptions-item label="Comment">
          {{ currentEvaluation.comment || 'No comments' }}
        </el-descriptions-item>
        <el-descriptions-item label="Evaluation Time">
          {{ currentEvaluation.evaluationTime }}
        </el-descriptions-item>
        <el-descriptions-item>
          <el-button type="warning" @click="editEvaluation">Edit Evaluation</el-button>
          <el-button type="danger" @click="deleteEvaluation">Delete Evaluation</el-button>
        </el-descriptions-item>
      </el-descriptions>
    </div>
  </div>

  <!-- Subtasks List -->
  <div class="subtasks-section" v-if="currentTask">
    <div class="section-header">
      <h3>Sub-task List</h3>
      <div class="button-group">
        <el-button type="primary" size="small" @click="addSubTaskForCurrentTask">
          <el-icon><Plus /></el-icon>Add Sub-task
        </el-button>
      </div>
    </div>
    <div v-loading="subTasksLoading">
      <el-table
          :data="subTasks"
          border
          style="width: 100%; margin-top: 15px;"
          v-if="subTasks.length > 0"
      >
        <el-table-column prop="title" label="Sub-task Title" min-width="150" />
        <el-table-column prop="assigneeName" label="Assigned Student" width="120">
          <template #default="scope">
            <span v-if="scope.row.assigneeName">{{ scope.row.assigneeName }}</span>
            <el-tag v-else type="info">Unassigned</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="Priority" width="100">
          <template #default="scope">
            <el-tag :type="getPriorityType(scope.row.priority)">
              {{ scope.row.priority || 'Medium' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="Status" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" width="150">
          <template #default="scope">
            <el-button type="warning" size="small" @click="editTask(scope.row)">
              <el-icon><Edit /></el-icon>Edit
            </el-button>
            <el-popconfirm
                title="Are you sure to delete this subtask?"
                @confirm="deleteTaskItem(scope.row.id)"
            >
              <template #reference>
                <el-button type="danger" size="small">
                  <el-icon><Delete /></el-icon>Delete
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div v-else class="empty-subtasks">
        <el-empty description="No subtasks available" :image-size="80">
          <template #description>
            <p>No subtasks are available for this task</p>
          </template>
        </el-empty>
      </div>
    </div>
  </div>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="detailsDialogVisible = false">Close</el-button>
      <el-button
          type="success"
          @click="openAssignDialog(currentTask)"
          :disabled="!!currentTask?.assigneeId"
      >
        Assign to Student
      </el-button>
      <el-button type="primary" @click="editTask(currentTask)">Edit Task</el-button>
    </div>
  </template>
</el-dialog>

<!-- Create/Edit Task Dialog -->
<el-dialog
    v-model="taskFormDialogVisible"
    :title="isEditing ? 'Edit Task' : 'Create Task'"
    width="60%"
    destroy-on-close
>
  <el-form
      ref="taskFormRef"
      :model="taskForm"
      :rules="taskRules"
      label-width="100px"
  >
    <el-form-item label="Task Title" prop="title" required>
      <el-input v-model="taskForm.title" placeholder="Please enter task title" />
    </el-form-item>
    <el-form-item label="Task Description" prop="description">
      <el-input
          v-model="taskForm.description"
          placeholder="Please enter task description"
          type="textarea"
          :rows="4"
      />
    </el-form-item>
    <el-form-item label="Priority" prop="priority">
      <el-select v-model="taskForm.priority" placeholder="Please select priority">
        <el-option label="High" value="High" />
        <el-option label="Medium" value="Medium" />
        <el-option label="Low" value="Low" />
      </el-select>
    </el-form-item>
    <el-form-item label="Time Range" prop="timeRange">
      <div style="display: flex; gap: 10px; align-items: center;">
        <el-date-picker
            v-model="startTime"
            type="datetime"
            placeholder="Start Time"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 0, 1, 9, 0, 0)"
            style="width: 100%;"
            :disabled-date="disabledDate"
            @change="validateTimeRange"
        />
        <span>to</span>
        <el-date-picker
            v-model="endTime"
            type="datetime"
            placeholder="End Time"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="new Date(2000, 0, 1, 18, 0, 0)"
            style="width: 100%;"
            :disabled-date="isEndTimeValid"
            @change="validateTimeRange"
        />
      </div>
    </el-form-item>
  </el-form>

  <!-- Subtasks Form Section -->
  <div class="subtasks-form-section" v-if="taskForm.hasSubtasks">
    <div class="section-header">
      <h3>Subtasks</h3>
      <div class="button-group">
        <el-button type="primary" size="small" @click="openNewSubTaskDialog">
          <el-icon><Plus /></el-icon>Add Subtask
        </el-button>
        <el-button type="success" size="small" @click="openBatchSelectTasksDialog">
          <el-icon><Plus /></el-icon>Batch Select Subtasks
        </el-button>
      </div>
    </div>

    <el-table
        :data="newTaskList"
        border
        style="width: 100%; margin-top: 15px;"
    >
      <el-table-column prop="title" label="Subtask Title" min-width="150" />
      <el-table-column prop="status" label="Status" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="Priority" width="100">
        <template #default="scope">
          <el-tag :type="getPriorityType(scope.row.priority)">
            {{ scope.row.priority || 'Medium' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="Actions" width="150">
        <template #default="scope">
          <el-button type="warning" size="small" @click="editNewSubTask(scope.$index)">
            <el-icon><Edit /></el-icon>Edit
          </el-button>
          <el-button type="danger" size="small" @click="removeNewSubTask(scope.$index)">
            <el-icon><Delete /></el-icon>Delete
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-if="newTaskList.length === 0" class="empty-tasks-tip">
      <el-empty description='No subtasks available, please click "Add Subtask" to create' />
    </div>
  </div>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="taskFormDialogVisible = false">Cancel</el-button>
      <el-button type="primary" @click="submitTaskForm">Confirm</el-button>
    </div>
  </template>
</el-dialog>

<!-- Add Subtasks Dialog when Creating Project -->
<el-dialog
    v-model="newSubTaskFormVisible"
    :title="editingSubTaskIndex >= 0 ? 'Edit Task' : 'Add Task'"
    width="50%"
    destroy-on-close
>
  <el-form
      ref="newSubTaskFormRef"
      :model="newSubTaskForm"
      label-width="100px"
  >
    <el-form-item label="Task Title" prop="title" required>
      <el-input v-model="newSubTaskForm.title" placeholder="Please enter task title" />
    </el-form-item>
    <el-form-item label="Task Description" prop="description">
      <el-input
          v-model="newSubTaskForm.description"
          placeholder="Please enter task description"
          type="textarea"
          :rows="4"
      />
    </el-form-item>
    <el-form-item label="Priority" prop="priority">
      <el-select v-model="newSubTaskForm.priority" placeholder="Please select priority">
        <el-option label="High" value="High" />
        <el-option label="Medium" value="Medium" />
        <el-option label="Low" value="Low" />
      </el-select>
    </el-form-item>
    <el-form-item label="Status" prop="status" v-if="editingSubTaskIndex >= 0">
      <el-select v-model="newSubTaskForm.status" placeholder="Please select status">
        <el-option label="Not Started" value="Not Started" />
        <el-option label="In Progress" value="In Progress" />
        <el-option label="Completed" value="Completed" />
      </el-select>
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="newSubTaskFormVisible = false">Cancel</el-button>
      <el-button type="primary" @click="addNewSubTask">Confirm</el-button>
    </div>
  </template>
</el-dialog>

<!-- Batch Select Tasks Dialog -->
<el-dialog
    v-model="batchSelectTasksVisible"
    title="Batch Select Tasks"
    width="70%"
    destroy-on-close
>
  <div v-loading="availableTasksLoading">
    <el-input
        v-model="taskSearchQuery"
        placeholder="Search tasks..."
        prefix-icon="el-icon-search"
        clearable
        style="margin-bottom: 15px;"
    />

    <el-table
        :data="filteredAvailableTasks"
        border
        style="width: 100%"
        @selection-change="handleTaskSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="title" label="Task Title" min-width="150" />
      <el-table-column prop="status" label="Status" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="priority" label="Priority" width="100">
        <template #default="scope">
          <el-tag :type="getPriorityType(scope.row.priority)">
            {{ scope.row.priority || 'Medium' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="Description" min-width="200" show-overflow-tooltip />
    </el-table>
  </div>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="batchSelectTasksVisible = false">Cancel</el-button>
      <el-button type="primary" @click="addSelectedSubTasks">Confirm</el-button>
    </div>
  </template>
</el-dialog>

<!-- Assign Task Dialog -->
<el-dialog
    v-model="assignDialogVisible"
    title="Assign Task to Student"
    width="40%"
    destroy-on-close
>
  <el-select
      v-model="selectedStudentId"
      placeholder="Please select a student"
      style="width: 100%"
      v-loading="studentsLoading"
  >
    <el-option
        v-for="student in students"
        :key="student.id"
        :label="student.name"
        :value="student.id"
    />
  </el-select>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="assignDialogVisible = false">Cancel</el-button>
      <el-button type="primary" @click="handleAssignTask">Confirm Assign</el-button>
    </div>
  </template>
</el-dialog>

<!-- Task Submission Records Dialog -->
<el-dialog
    v-model="submissionsDialogVisible"
    title="Task Submission Records"
    width="70%"
    destroy-on-close
>
  <div v-if="currentTask" class="task-info">
    <h3>Task Information</h3>
    <el-descriptions :column="2" border>
      <el-descriptions-item label="Task Title">{{ currentTask.title }}</el-descriptions-item>
      <el-descriptions-item label="Task Status">
        <el-tag :type="getStatusType(currentTask.status)">
          {{ currentTask.status }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="Student">{{ currentTask.assigneeName || 'Unassigned' }}</el-descriptions-item>
      <el-descriptions-item label="Start Time">{{ currentTask.startTime || 'Not Set' }}</el-descriptions-item>
    </el-descriptions>
  </div>

  <div v-if="submissions.length > 0" class="submission-list">
    <h3>Submission Records ({{submissions.length}})</h3>
    <el-table :data="submissions" border style="width: 100%">
      <el-table-column prop="originalFilename" label="Filename" min-width="200" />
      <el-table-column prop="fileSize" label="Size" width="120">
        <template #default="scope">
          {{ formatFileSize(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column prop="fileType" label="Type" width="120" />
      <el-table-column prop="submitterName" label="Submitter" width="120" />
      <el-table-column prop="submissionTime" label="Submission Time" width="160" />
      <el-table-column label="Actions" width="180">
        <template #default="scope">
          <el-button type="primary" size="small" @click="downloadSubmission(scope.row)">
            Download
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <div v-else class="no-submissions">
    <el-empty description="No submission records" />
  </div>

  <template #footer>
    <div class="dialog-footer">
      <el-button @click="submissionsDialogVisible = false">Close</el-button>
    </div>
  </template>
</el-dialog>
</div>
<script setup lang="ts">
import { ref, computed, onMounted, watch, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useUserStore } from '../../stores/user';
import type { FormInstance, FormRules } from 'element-plus';
import {
  Search,
  View,
  Edit,
  Delete,
  CirclePlus,
  Plus,
  Document
} from '@element-plus/icons-vue';
import {
  createTask,
  updateTask,
  getTaskDetail,
  deleteTask,
  getSupervisorTasks,
  getSupervisorTasksByStatus,
  assignTaskToStudent,
  updateTaskStatus,
  getAvailableTasks,
  type Task,
  type TaskDTO,
  createBatchTasks,
  getTaskSubmissions,
  type TaskSubmission,
  evaluateTask,
  getTaskEvaluation,
  deleteTaskEvaluation,
  type TaskEvaluation
} from '../../api/task';
import { getStudents } from '../../api/student';
import type { Student } from '../../api/user';

const userStore = useUserStore();

// State variables
const loading = ref<boolean>(false);
const searchQuery = ref<string>('');
const currentPage = ref<number>(1);
const pageSize = ref<number>(10);
const totalTasks = ref<number>(0);
const tasks = ref<Task[]>([]);
const selectedTasks = ref<Task[]>([]);
const currentTask = ref<Task | null>(null);
const detailsDialogVisible = ref<boolean>(false);
const activeTab = ref<string>('all');

// Subtask-related variables
const subTasks = ref<Task[]>([]);
const subTasksLoading = ref<boolean>(false);

// Form-related variables
const taskFormRef = ref<FormInstance>();
const taskFormDialogVisible = ref<boolean>(false);
const isEditing = ref<boolean>(false);
const taskForm = ref({
  id: null as number | null,
  title: '',
  description: '',
  priority: 'Medium', // Default: Medium
  status: 'Not Started', // Default: Not Started
  supervisorId: userStore.user.id,
  projectId: null,
  assigneeId: null,
  completed: false
});
const startTime = ref<string | null>(null);
const endTime = ref<string | null>(null);

// Form validation rules
const taskRules = {
  title: [
    { required: true, message: 'Please enter the task title', trigger: 'blur' },
    { min: 2, max: 50, message: 'Length must be between 2 and 50 characters', trigger: 'blur' }
  ],
  status: [
    { required: true, message: 'Please select the task status', trigger: 'change' }
  ]
};

// Assignment-related variables
const assignDialogVisible = ref<boolean>(false);
const selectedStudentId = ref<number | null>(null);
const students = ref<Student[]>([]);
const studentsLoading = ref<boolean>(false);
const taskToAssign = ref<Task | null>(null);

// Add subtask-related variables
const newTaskList = ref<any[]>([]);
const newSubTaskFormVisible = ref<boolean>(false);
const newSubTaskForm = ref({
  title: '',
  description: '',
  priority: 'Medium', // Default: Medium
  status: 'Not Started' // Default: Not Started
});
const editingSubTaskIndex = ref<number>(-1);
const newSubTaskFormRef = ref<FormInstance>();

// Batch select task dialog-related variables
const batchSelectTasksVisible = ref<boolean>(false);
const availableTasksLoading = ref<boolean>(false);
const taskSearchQuery = ref<string>('');
const availableTasks = ref<Task[]>([]);
const selectedSubTasks = ref<Task[]>([]);

// Task submission records
const submissionsDialogVisible = ref<boolean>(false);
const submissions = ref<TaskSubmission[]>([]);

// Evaluation-related state
const currentEvaluation = ref<TaskEvaluation | null>(null);
const evaluationForm = ref({
  score: 5,
  comment: ''
});
const evaluationLoading = ref<boolean>(false);

// Calculate filtered available tasks
const filteredAvailableTasks = computed(() => {
  if (!taskSearchQuery.value) return availableTasks.value;

  const query = taskSearchQuery.value.toLowerCase();
  return availableTasks.value.filter(task =>
      task.title?.toLowerCase().includes(query) ||
      task.description?.toLowerCase().includes(query)
  );
});

// Initialize data
onMounted(() => {
  fetchTasks();
});

// Fetch task data
const fetchTasks = async () => {
  loading.value = true;
  try {
    let data;
    if (activeTab.value === 'all') {
      data = await getSupervisorTasks(userStore.user.id);
    } else {
      data = await getSupervisorTasksByStatus(userStore.user.id, activeTab.value);
    }
    // Filter out subtasks (tasks with a parentTaskId)
    let filteredTasks = data.filter(task => !task.parentTaskId);
    
    // Modify sort logic:
    // 1. By status priority: Unassigned -> In Progress -> Waiting for check -> Completed
    // 2. Same status sorted by deadline
    filteredTasks.sort((a, b) => {
      // Define status priority
      const getStatusPriority = (task) => {
        // Unassigned tasks (no student assigned or not started status)
        if (!task.assigneeId || task.status === 'Not Started') {
          return 0;
        }
        // In progress tasks
        if (task.status === 'In Progress') {
          return 1;
        }
        // Tasks waiting for check (waiting for review status)
        if (task.reviewNeeded) {
          return 2;
        }
        // Completed tasks
        if (task.completed) {
          return 3;
        }
        return 0; // Default to highest priority
      };
      
      const priorityA = getStatusPriority(a);
      const priorityB = getStatusPriority(b);
      
      // Sort by status priority
      if (priorityA !== priorityB) {
        return priorityA - priorityB;
      }
      
      // Same status, sort by deadline
      return new Date(a.endTime || '9999-12-31') - new Date(b.endTime || '9999-12-31');
    });
    
    // Check and automatically update overdue task status
    filteredTasks.forEach(task => {
      if (task.endTime && task.status !== 'Completed') {
        const endDate = new Date(task.endTime);
        const now = new Date();
        if (endDate < now) {
          // Task is overdue, automatically update status to Completed
          updateTaskStatus(task.id, 'Completed');
          task.status = 'Completed';
        }
      }
    });
    
    tasks.value = filteredTasks;
    totalTasks.value = tasks.value.length;
    ElMessage.success('Successfully retrieved task data');
  } catch (error) {
    console.error('Failed to retrieve task data:', error);
    ElMessage.error('Failed to retrieve task data, please try again later');
  } finally {
    loading.value = false;
  }
};

// Get student list
const fetchStudents = async () => {
  studentsLoading.value = true;
  try {
    const data = await getStudents();
    students.value = data;
  } catch (error) {
    console.error('Failed to retrieve student list:', error);
    ElMessage.error('Failed to retrieve student list');
  } finally {
    studentsLoading.value = false;
  }
};

// Filter tasks based on search query
const filteredTasks = computed(() => {
  let filtered = [...tasks.value];

  // Filter by tab
  if (activeTab.value === 'review') {
    filtered = filtered.filter(task => task.reviewNeeded);
  } else if (activeTab.value !== 'all') {
    filtered = filtered.filter(task => {
      if (activeTab.value === 'completed') {
        return task.completed;
      } else if (activeTab.value === 'in_progress') {
        return !task.completed && (task.submissionCount > 0 || task.reviewNeeded);
      }
      return true;
    });
  }

  // Search filter
  if (searchQuery.value.trim()) {
    const query = searchQuery.value.toLowerCase();
    filtered = filtered.filter(task => {
      return (
        task.title.toLowerCase().includes(query) ||
        (task.description && task.description.toLowerCase().includes(query)) ||
        (task.assigneeName && task.assigneeName.toLowerCase().includes(query))
      );
    });
  }

  // Update total
  totalTasks.value = filtered.length;
  
  // Pagination
  if (currentPage.value > 1 && filtered.length <= (currentPage.value - 1) * pageSize.value) {
    currentPage.value = 1;
  }

  // Apply pagination
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filtered.slice(start, end);
});

// Handler functions
const handleSearch = () => {
  currentPage.value = 1;
};

const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  currentPage.value = 1;
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
};

const handleTabClick = () => {
  fetchTasks();
};

// View task details
const viewTaskDetails = async (task: Task) => {
  currentTask.value = task;
  detailsDialogVisible.value = true;

  // Load subtasks
  await loadSubTasks(task.id);

  // If the task is completed, load evaluation information
  if (task.completed) {
    await loadTaskEvaluation(task.id);
  }
};

// Create task
const openCreateTaskDialog = async (projectId = null) => {
  // Reset form
  resetTaskForm();
  isEditing.value = false;
  
  // If project ID is provided, check project status
  if (projectId) {
    try {
      const project = await getProjectDetail(projectId);
      if (project && project.status === 'Waiting for Review') {
        ElMessage.error('Cannot create tasks for a project that is waiting for review');
        return;
      }
      // Set project ID
      taskForm.value.projectId = projectId;
    } catch (error) {
      console.error('Error checking project status:', error);
    }
  }
  
  // Only show dialog when project status allows
  taskFormDialogVisible.value = true;
};

// Edit task
const editTask = async (task: Task) => {
  if (!task) return;
  
  // Check if the task's associated project is in "Waiting for Review" status
  if (task.projectId) {
    try {
      const project = await getProjectDetail(task.projectId);
      if (project && project.status === 'Waiting for Review') {
        ElMessage.error('Cannot edit tasks for a project that is waiting for review');
        return;
      }
    } catch (error) {
      console.error('Error checking project status:', error);
    }
  }
  
  isEditing.value = true;
  taskForm.value = {
    id: task.id,
    title: task.title,
    description: task.description || '',
    priority: task.priority || 'Medium',
    status: task.status,
    supervisorId: task.supervisorId,
    projectId: task.projectId,
    assigneeId: task.assigneeId,
    completed: task.completed || false
  };
  
  // Set time values
  startTime.value = task.startTime;
  endTime.value = task.endTime;
  
  // Fetch subtasks if needed
  if (task.id) {
    // If subtasks need to be retrieved, add relevant logic here
  }
  
  console.log('Editing task form data:', taskForm.value);
  taskFormDialogVisible.value = true;
};

// Submit task form
const submitTaskForm = () => {
  if (!taskFormRef.value) return;

  taskFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;

      try {
                // Check if the task's associated project is in "Waiting for Review" status
        if (taskForm.value.projectId) {
          try {
            const project = await getProjectDetail(taskForm.value.projectId);
            if (project && project.status === 'Waiting for Review') {
              ElMessage.error('Cannot create task for a project that is waiting for review');
              loading.value = false;
              return;
            }
          } catch (error) {
            console.error('Error checking project status:', error);
          }
        }

        const taskData = {
          ...taskForm.value
        };

        // Add time range
        if (startTime.value && endTime.value) {
          taskData.startTime = startTime.value;
          taskData.endTime = endTime.value;
        }

                // For new tasks, force the status to be "Not Started"
        if (!isEditing.value) {
          taskData.status = 'Not Started';
        }

        // If creating sub-tasks, add them to the task data
        if (taskForm.value.hasSubtasks && newTaskList.value.length > 0) {
          taskData.subtasks = newTaskList.value;
        }
        
        const isSuccess = isEditing.value 
          ? await handleUpdateTask(taskData)
          : await handleCreateTask(taskData);
        
        if (isSuccess) {
          taskFormDialogVisible.value = false;
          await refreshTaskList();
          ElMessage.success(`${isEditing.value ? 'Updated' : 'Created'} task successfully`);
        }
      } catch (error) {
        console.error('Task form validation failed:', error);
        ElMessage.error('Please fill in all required fields correctly');
      }
    }
  });
};

// Delete task
const deleteTaskItem = async (id: number) => {
  loading.value = true;
  try {
    const success = await deleteTask(id);
    if (success) {
      ElMessage.success('Task deleted successfully');
      tasks.value = tasks.value.filter(task => task.id !== id);
      totalTasks.value = tasks.value.length;

      // If viewing task details, refresh subtask list
      if (detailsDialogVisible.value && currentTask.value) {
        refreshSubTasks();
      }
    } else {
      ElMessage.error('Failed to delete task');
    }
  } catch (error) {
    console.error('Failed to delete task:', error);
    ElMessage.error('Failed to delete task');
  } finally {
    loading.value = false;
  }
};

// Assign task to student
const openAssignDialog = (task: Task) => {
  if (task.assigneeId) {
    ElMessage.warning('This task has already been assigned to a student');
    return;
  }

  taskToAssign.value = task;
  selectedStudentId.value = null;
  fetchStudents();
  assignDialogVisible.value = true;
};

const handleAssignTask = async () => {
  if (!taskToAssign.value || !selectedStudentId.value) {
    ElMessage.warning('Please select a student to assign to');
    return;
  }

  loading.value = true;
  try {
    const result = await assignTaskToStudent(taskToAssign.value.id, selectedStudentId.value);
    ElMessage.success('Task assigned successfully');
    assignDialogVisible.value = false;

    // Update local data
    const index = tasks.value.findIndex(t => t.id === taskToAssign.value?.id);
    if (index !== -1) {
      tasks.value[index] = result;
    }

    // If currently on the details page, also update the current task
    if (currentTask.value && currentTask.value.id === taskToAssign.value.id) {
      currentTask.value = result;
    }

    taskToAssign.value = null;
  } catch (error) {
    console.error('Failed to assign task:', error);
    ElMessage.error('Failed to assign task');
  } finally {
    loading.value = false;
  }
};

// Helper functions
const getStatusType = (status: string): 'primary' | 'success' | 'warning' | 'danger' | 'info' => {
  switch (status) {
    case 'Not Started': return 'info';
    case 'In Progress': return 'primary';
    case 'Waiting for Review': return 'warning';
    case 'Completed': return 'success';
    case 'Draft': return 'info';
    case 'Midterm': return 'warning';
    case 'Final': return 'success';
    default: return 'primary';
  }
};

const getPriorityType = (priority: string): 'primary' | 'success' | 'warning' | 'danger' => {
  switch (priority) {
    case 'High': return 'danger'; // High
    case 'Medium': return 'warning'; // Medium
    case 'Low': return 'success'; // Low
    default: return 'warning';
  }
};

// Add subtask dialog
const openNewSubTaskDialog = () => {
  // Reset index
  editingSubTaskIndex.value = -1;

  // Initialize task form
  newSubTaskForm.value = {
    title: '',
    description: '',
    priority: 'Medium', // Default: Medium
    status: 'Not Started' // Default: Not Started
  };

  // Open dialog
  newSubTaskFormVisible.value = true;
};

// Add new subtask
const addNewSubTask = async () => {
  if (!newSubTaskForm.value.title || newSubTaskForm.value.title.trim() === '') {
    ElMessage.warning('Please enter the task title');
    return;
  }

  // If adding a subtask in task details
  if (detailsDialogVisible.value && currentTask.value) {
    loading.value = true;
    try {
      // Create subtask data
      const subTaskData = {
        ...newSubTaskForm.value,
        supervisorId: userStore.user.id,
        parentTaskId: currentTask.value.id
      };

      // Create subtask directly
      await createTask(subTaskData);
      ElMessage.success('Subtask created successfully');

      // Refresh subtask list
      await refreshSubTasks();

      // Close dialog
      newSubTaskFormVisible.value = false;
    } catch (error) {
      console.error('Failed to create subtask:', error);
      ElMessage.error('Failed to create subtask');
    } finally {
      loading.value = false;
    }
    return;
  }

  // If editing a subtask, update that task
  if (editingSubTaskIndex.value >= 0) {
    newTaskList.value[editingSubTaskIndex.value] = {...newSubTaskForm.value};
    editingSubTaskIndex.value = -1;
  } else {
    // Otherwise add a new subtask
    newTaskList.value.push({...newSubTaskForm.value});
  }

  // Reset form
  newSubTaskForm.value = {
    title: '',
    description: '',
    priority: 'Medium', // Default: Medium
    status: 'Not Started' // Default: Not Started
  };

  // Close dialog
  newSubTaskFormVisible.value = false;
};

// Edit subtask when creating a task
const editNewSubTask = (index: number) => {
  // Set the editing index
  editingSubTaskIndex.value = index;

  // Set the form data
  const task = newTaskList.value[index];
  newSubTaskForm.value = {
    title: task.title,
    description: task.description || '',
    priority: task.priority || 'Medium', // Default: Medium
    status: task.status || 'Not Started' // Default: Not Started
  };

  // Open dialog
  newSubTaskFormVisible.value = true;
};

// Remove subtask when creating a task
const removeNewSubTask = (index: number) => {
  newTaskList.value.splice(index, 1);
};

// Batch select task related functions
// Open the batch select task dialog
const openBatchSelectTasksDialog = async () => {
  // Clear selected tasks
  selectedSubTasks.value = [];

  // Load available tasks
  availableTasksLoading.value = true;
  try {
    availableTasks.value = await getAvailableTasks(userStore.user.id);
  } catch (error) {
    console.error('Failed to retrieve available tasks:', error);
    ElMessage.error('Failed to retrieve available tasks');
  } finally {
    availableTasksLoading.value = false;
  }

  batchSelectTasksVisible.value = true;
};

// Handle task selection change
const handleTaskSelectionChange = (selected: Task[]) => {
  selectedSubTasks.value = selected;
};

// Add selected tasks to the task list
const addSelectedSubTasks = () => {
  if (selectedSubTasks.value.length === 0) {
    ElMessage.warning('Please select at least one task');
    return;
  }

  // Add the selected tasks to the new project task list
  selectedSubTasks.value.forEach(task => {
    // Check if the same task has already been added
    const exists = newTaskList.value.some(t =>
        t.title === task.title && t.description === task.description
    );

    if (!exists) {
      newTaskList.value.push({
        title: task.title,
        description: task.description,
        priority: task.priority || 'Medium', // Default: Medium
        status: task.status || 'Not Started' // Default: Not Started
      });
    }
  });

  ElMessage.success(`Added ${selectedSubTasks.value.length} tasks`);
  batchSelectTasksVisible.value = false;
};

// Refresh subtask list
const refreshSubTasks = async () => {
  if (!currentTask.value) return;

  subTasksLoading.value = true;
  try {
    const allTasks = await getSupervisorTasks(userStore.user.id);
    const filteredSubTasks = allTasks.filter(t => t.parentTaskId === currentTask.value?.id);
    
    // Sort subtasks by end time
    filteredSubTasks.sort((a, b) => {
      // First sort by end time
      if (a.endTime && b.endTime) {
        const dateA = new Date(a.endTime);
        const dateB = new Date(b.endTime);
        return dateB.getTime() - dateA.getTime(); // descending order, tasks ending soonest come first
      } else if (a.endTime) {
        return -1; // a has end time but b doesn't, a comes first
      } else if (b.endTime) {
        return 1;  // b has end time but a doesn't, b comes first
      } else {
        // If neither task has an end time, sort by create time
        const dateA = a.createTime ? new Date(a.createTime) : new Date(0);
        const dateB = b.createTime ? new Date(b.createTime) : new Date(0);
        return dateB.getTime() - dateA.getTime();
      }
    });
    
    // Check and automatically update overdue subtask status
    filteredSubTasks.forEach(task => {
      if (task.endTime && task.status !== 'Completed') {
        const endDate = new Date(task.endTime);
        const now = new Date();
        if (endDate < now) {
          // Task is overdue, automatically update status to Completed
          updateTaskStatus(task.id, 'Completed');
          task.status = 'Completed';
        }
      }
    });
    
    subTasks.value = filteredSubTasks;
  } catch (error) {
    console.error('Failed to retrieve subtasks:', error);
    ElMessage.warning('Failed to retrieve subtask information');
    subTasks.value = [];
  } finally {
    subTasksLoading.value = false;
  }
};

// Add subtask to the current task
const addSubTaskForCurrentTask = () => {
  // Reset index
  editingSubTaskIndex.value = -1;

  // Initialize task form
  newSubTaskForm.value = {
    title: '',
    description: '',
    priority: 'Medium', // Default: Medium
    status: 'Not Started' // Default: Not Started
  };

  // Open dialog
  newSubTaskFormVisible.value = true;
};

// Add action to view submission records in the task action section
const viewTaskSubmissions = async (task: Task) => {
  currentTask.value = task;
  submissionsDialogVisible.value = true;
  submissions.value = []; // Clear previous data

  try {
    console.log('Starting to retrieve task submission records, Task ID:', task.id);
    const result = await getTaskSubmissions(task.id);

    if (result && result.length > 0) {
      console.log('Retrieved submission records count:', result.length);
      console.log('Submission record details:', JSON.stringify(result[0]));
      submissions.value = result;
    } else {
      console.log('No submission records for this task');
    }
  } catch (error) {
    console.error('Failed to retrieve task submission records:', error);
    ElMessage.error('Failed to retrieve task submission records');
  }
};

// Download submission file
const downloadSubmission = (submission: TaskSubmission) => {
  try {
    console.log('Starting to download file:', submission);

    // Get authorization token
    const token = localStorage.getItem('token');
    if (!token) {
      ElMessage.error('Authorization has expired, please log in again');
      return;
    }

    // Create an <a> tag to download the file
    const link = document.createElement('a');
    link.href = `/api/supervisor/submissions/${submission.id}/download`;
    link.setAttribute('download', submission.originalFilename);

    // To ensure the request includes the authorization header, we use Fetch API
    fetch(link.href, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
        .then(response => {
          if (!response.ok) {
            throw new Error(`Download failed: ${response.status}`);
          }
          return response.blob();
        })
        .then(blob => {
          // Create download link
          const url = window.URL.createObjectURL(blob);
          const downloadLink = document.createElement('a');
          downloadLink.href = url;
          downloadLink.download = submission.originalFilename;
          document.body.appendChild(downloadLink);
          downloadLink.click();
          window.URL.revokeObjectURL(url);
          document.body.removeChild(downloadLink);

          ElMessage.success('File downloaded successfully');
        })
        .catch(error => {
          console.error('Failed to download file:', error);
          ElMessage.error(`Failed to download file: ${error.message}`);
        });
  } catch (error) {
    console.error('Failed to download file operation:', error);
    ElMessage.error('Failed to download file');
  }
};

// Format file size
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B';
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(2) + ' KB';
  } else {
    return (size / 1024 / 1024).toFixed(2) + ' MB';
  }
};

// Get task evaluation
const loadTaskEvaluation = async (taskId: number) => {
  try {
    evaluationLoading.value = true;
    const evaluation = await getTaskEvaluation(taskId);
    currentEvaluation.value = evaluation;
  } catch (error: any) {
    // Ignore 404 or no data errors, because the task may not have been evaluated yet
    if (error.response && error.response.status === 404) {
      console.log('The task does not have an evaluation yet, this is normal');
      currentEvaluation.value = null;

      // Reset the evaluation form to the default values
      evaluationForm.value.score = 5;
      evaluationForm.value.comment = '';
    } else if (!error.response || error.response.status !== 404) {
      console.error('Failed to retrieve task evaluation:', error);
      // Do not display error message, but handle silently
      currentEvaluation.value = null;

      // Reset the evaluation form to the default values
      evaluationForm.value.score = 5;
      evaluationForm.value.comment = '';
    }
  } finally {
    evaluationLoading.value = false;
  }
};

// Submit evaluation
const submitEvaluation = async () => {
  if (!currentTask.value) return;

  try {
    evaluationLoading.value = true;
    console.log('Submitting evaluation data:', {
      taskId: currentTask.value.id,
      score: evaluationForm.value.score,
      comment: evaluationForm.value.comment
    });

    const response = await evaluateTask(
        currentTask.value.id,
        evaluationForm.value.score,
        evaluationForm.value.comment
    );
    currentEvaluation.value = response;
    ElMessage.success('Evaluation submitted successfully');
    
    // Refresh task information after successful evaluation
    fetchTasks();
    
    // Update the corresponding task in the task list
    if (currentTask.value) {
      const updatedTask = await getTaskById(currentTask.value.id);
      currentTask.value = updatedTask;
      
      // Update the task list with the updated task
      const index = tasks.value.findIndex(t => t.id === currentTask.value?.id);
      if (index !== -1) {
        tasks.value[index] = updatedTask;
      }
    }
  } catch (error: any) {
    console.error('Failed to submit evaluation:', error);
    ElMessage.error(`Failed to submit evaluation: ${error.message || 'Unknown error'}`);
  } finally {
    evaluationLoading.value = false;
  }
};

// Edit evaluation
const editEvaluation = () => {
  if (currentEvaluation.value) {
    evaluationForm.value.score = currentEvaluation.value.score;
    evaluationForm.value.comment = currentEvaluation.value.comment || '';
    currentEvaluation.value = null;
  }
};

// Delete evaluation
const deleteEvaluation = async () => {
  if (!currentTask.value) return;

  try {
    await ElMessageBox.confirm('Are you sure you want to delete this evaluation?', 'Confirmation', {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
      type: 'warning'
    });

    evaluationLoading.value = true;
    await deleteTaskEvaluation(currentTask.value.id);
    currentEvaluation.value = null;

    // Reset the evaluation form to the default values
    evaluationForm.value.score = 5;
    evaluationForm.value.comment = '';

    ElMessage.success('Evaluation deleted');
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('Failed to delete evaluation:', error);
      ElMessage.error(`Failed to delete evaluation: ${error.message || 'Unknown error'}`);
    }
  } finally {
    evaluationLoading.value = false;
  }
};

// Load subtasks
const loadSubTasks = async (taskId: number) => {
  subTasksLoading.value = true;
  try {
    // Filter out tasks with parentTaskId equal to the current task ID from all tasks
    const allTasks = await getSupervisorTasks(userStore.user.id);
    const filteredSubTasks = allTasks.filter(t => t.parentTaskId === taskId);
    
    // Sort subtasks by end time
    filteredSubTasks.sort((a, b) => {
      // First sort by end time
      if (a.endTime && b.endTime) {
        const dateA = new Date(a.endTime);
        const dateB = new Date(b.endTime);
        return dateB.getTime() - dateA.getTime(); // descending order, tasks ending soonest come first
      } else if (a.endTime) {
        return -1; // a has end time but b doesn't, a comes first
      } else if (b.endTime) {
        return 1;  // b has end time but a doesn't, b comes first
      } else {
        // If neither task has an end time, sort by create time
        const dateA = a.createTime ? new Date(a.createTime) : new Date(0);
        const dateB = b.createTime ? new Date(b.createTime) : new Date(0);
        return dateB.getTime() - dateA.getTime();
      }
    });
    
    // Check and automatically update overdue subtask status
    filteredSubTasks.forEach(task => {
      if (task.endTime && task.status !== 'Completed') {
        const endDate = new Date(task.endTime);
        const now = new Date();
        if (endDate < now) {
          // Task is overdue, automatically update status to Completed
          updateTaskStatus(task.id, 'Completed');
          task.status = 'Completed';
        }
      }
    });
    
    subTasks.value = filteredSubTasks;
  } catch (error) {
    console.error('Failed to retrieve subtasks:', error);
    ElMessage.warning('Failed to retrieve subtask information');
    subTasks.value = [];
  } finally {
    subTasksLoading.value = false;
  }
};

// Add time validation function
function disabledDate(time) {
  // Disable dates smaller than current time
  return time.getTime() < Date.now() - 8.64e7; // 8.64e7 is the number of milliseconds in a day, allows selecting today
}

// Add time range validation function
function validateTimeRange() {
  if (startTime.value && endTime.value) {
    const start = new Date(startTime.value).getTime();
    const end = new Date(endTime.value).getTime();
    if (start > end) {
      ElMessage.error('End time cannot be earlier than start time');
      endTime.value = null;
      return false;
    }
  }
  return true;
}

// Add task status update function
async function updateTaskStatus(taskId, newStatus) {
  try {
    const result = await updateTask(taskId, { status: newStatus });
    console.log('Task status updated:', result);
  } catch (error) {
    console.error('Failed to update task status:', error);
  }
}

// Add end time validation function
function isEndTimeValid(time) {
  const now = Date.now() - 8.64e7; // Allows selecting today
  
  // If no start time is selected, only disable past dates
  if (!startTime.value) {
    return time.getTime() < now;
  }
  
  // Disable dates earlier than start time or past dates
  const startDateTime = new Date(startTime.value).getTime();
  return time.getTime() < startDateTime || time.getTime() < now;
}

// Add calculation property, count pending review tasks
const tasksPendingReviewCount = computed(() => {
  return tasks.value.filter(task => task.reviewNeeded).length;
});

const calculateTaskProgress = (task) => {
  if (!task) return 0;
  
  // If the task is completed or status is completed, return 100%
  if (task.completed || task.status === 'Completed') {
    return 100;
  }
  
  // Check if there are task submissions
  const hasSubmission = task.submissionCount && task.submissionCount > 0;
  if (hasSubmission) {
    return 100; // Tasks with submissions are shown as 100% complete
  }
  
  // Default returns 0%
  return 0;
};

// Add method to reset task form
const resetTaskForm = () => {
  taskForm.value = {
    id: null,
    title: '',
    description: '',
    priority: 'Medium', // Default: Medium
    status: 'Not Started', // Default: Not Started
    supervisorId: userStore.user.id,
    projectId: null,
    assigneeId: null,
    completed: false
  };
  startTime.value = null;
  endTime.value = null;

  // Clear task list
  newTaskList.value = [];
};
</script>
<style scoped>
.task-management {
  padding: 10px;
.task-management {
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.task-description {
  white-space: pre-wrap;
  max-height: 200px;
  overflow-y: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.task-tabs {
  margin-bottom: 15px;
}

.task-create-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.button-group {
  display: flex;
  gap: 10px;
}

.empty-tasks-tip {
  text-align: center;
  padding: 10px;
  color: #909399;
}

.sub-tasks-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.sub-tasks-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.empty-subtasks {
  text-align: center;
  padding: 20px;
  color: #909399;
}

.task-info,
.submission-list {
  margin-bottom: 20px;
}

h3 {
  margin-bottom: 15px;
  font-weight: 500;
  color: #303133;
}

.no-submissions {
  padding: 20px 0;
}

.task-evaluation-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.evaluation-details {
  margin-top: 15px;
}

.status-hint {
  margin-top: 8px;
  margin-bottom: 10px;
}

.status-hint .el-alert {
  padding: 8px 12px;
}
</style> 